package com.alipay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.config.AlipayConfig;
import com.alipay.model.request.RefundRequest;
import com.alipay.model.response.RefundResponse;
import com.alipay.service.AbstractPayService;

/**
 * @author lwj
 * @create 2025-11-10-0:16
 */
public class RefundServiceImpl extends AbstractPayService<RefundRequest, RefundResponse> {
    public RefundServiceImpl(AlipayClient alipayClient, AlipayConfig alipayConfig) {
        super(alipayClient, alipayConfig);
    }

    @Override
    protected AlipayRequest createAlipayRequest() {
        return new AlipayTradeRefundRequest();
    }

    @Override
    protected void fillBizContent(JSONObject bizContent, RefundRequest request) {
        // 添加退款金额
        bizContent.put("refund_amount", request.getRefundAmount());
        bizContent.put("refund_reason", request.getRefundReason());
        bizContent.put("out_request_no", request.getOutRequestNo());
    }

    @Override
    protected void setRequestParams(AlipayRequest alipayRequest, JSONObject bizContent) {
        AlipayTradeRefundRequest refundRequest = (AlipayTradeRefundRequest) alipayRequest;
        refundRequest.setBizContent(bizContent.toJSONString());
    }

    @Override
    protected AlipayResponse executeAlipayRequest(AlipayRequest alipayRequest) throws AlipayApiException {
        return alipayClient.execute((AlipayTradeRefundRequest) alipayRequest);
    }

    @Override
    protected RefundResponse handleAlipayResponse(AlipayResponse alipayResponse, RefundRequest request) {
        RefundResponse response = new RefundResponse();
        AlipayTradeRefundResponse refundResponse = (AlipayTradeRefundResponse) alipayResponse;
        return populateResponse(response, refundResponse);
    }

    @Override
    protected RefundResponse createEmptyResponse() {
        return new RefundResponse();
    }

    @Override
    protected String getProductCode() {
        return "";
    }

    @Override
    protected void populateSpecificFields(RefundResponse response, AlipayResponse alipayResponse) {
        AlipayTradeRefundResponse refundResponse = (AlipayTradeRefundResponse) alipayResponse;
        response.setTradeNo(refundResponse.getTradeNo());
        response.setRefundAmount(refundResponse.getPresentRefundBuyerAmount());
        response.setGmtRefundPay(refundResponse.getGmtRefundPay().toString());
    }
}
